#!/usr/bin/python
#__docformat__ = "restructuredtext en"
# ******NOTICE***************
# run.py script by Shoibal Chakravarty
#
# You may copy and use this module as you see fit with no
# guarantee implied provided you keep this notice in all copies.
# *****END NOTICE************
__author__ = "Shoibal Chakravarty (shoibalc@princeton.edu)"
__version__ = "0.1"
__date__ = " 2011/August"
__license__ = "BSD"


import sys
import argparse
#import optparse
try:
    import cPickle as pickle
except:
    import pickle

import src.dataops
import src.output
from src.myopic import myopic
from src.two_game import twomyopictwonash
from src.two_myopic import threemyopiconelookahead
from src.three_game import threenash
from src.three_opt import threeoptimized
from src.two_opt import twooptimized

######################################################
###  SELECT COUNTRIES FOR DIFFERENT SCENARIOS HERE ###

REGION =       ['EU','CHINA','USA','ROW']

# MYOPIC          M     M      M     M
# LOOK AHEAD      L     M      M     M
#2 NASH           N     N      M     M
#3 NASH           N     N      N     M
#2 OPTIMIZED      O     O      M     M
#3 OPTIMIZED      O     O      O     M

# In the table above, M means MYOPIC (ROW is always MYOPIC).
# The rows show the strategies for various scenarios. 
# Change REGION to try other combinations.
# Eg. ['CHINA','EU','USA','ROW'] will have CHINA look ahead in the 
# LOOK AHEAD scenario. 

#  Set up the command line parser that provides some options for picking scenarios to run.

parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,
        description = \
'''
This program simulates strategic investments in green energy by three regions 
under various scenarios. There are two sources of energy: green and fossil. 
Green energy is initially significantly more expensive than fossil but the
cost goes down with deployment under \'learning by doing\'.

The following scenarios are simulated:

    Myopic: Regions make investment decisions for the current 
    period only and are unaware of each others decisions.

    One Region Looks Ahead: One region make investment decision
    for the current and next period but the other two invest 
    myopically.

    Two Nash: Two regions invest strategically for the current 
    and the next period (myopic in the second and Nash in the first) 
    whereas the third region invests myopically.

    Three Nash: All three regions invest strategically for the
    current and the next period (myopic in the second and Nash
    in the first).

    Two Optimized: Two regions cooperate to invest in the current
    and next period to maximize the sum of their individual utility functions. 
    The third region invests myopically.

    Three Optimized: All three regions cooperate to invest in the
    current and next period to maximize the sum of their individual
    utility functions.

usage: run.py [options (default: all options)] [-r RESULTS_FILE] DATA_FILE

''',\
        usage = '%(prog)s [options (default: all options)] [-r RESULTS_FILE] DATA_FILE')
parser.add_argument('-n', '--twonash', action = "store_true", dest = "twonash", default = False,  help = "Run \'Two Nash\'")
parser.add_argument('-N', '--threenash', action = "store_true", dest = "threenash", default = False, help = "Run \'Three Nash\'")
parser.add_argument('-o', '--twoopt', action = "store_true", dest = "twoopt", default = False, help = "Run \'Two Optimized\'")
parser.add_argument('-O', '--threeopt', action = "store_true", dest = "threeopt", default = False, help = "Run \'Three Optimized\'")
parser.add_argument('-l', '--lookahead', action = "store_true", dest = "lookahead", default = False, help = "Run \'One Region Looks Ahead\'.")
parser.add_argument('DATA_FILE', action = "store", nargs='?', default = '', help = "Read data from the file DATA_FILE.")
parser.add_argument('-r', '--results', action = "store", dest = "outputfile", metavar = "RESULTS_FILE", default = "results.csv", \
        help = "Write results to file RESULTS_FILE (default: results.csv).")
parser.add_argument('-p','--pickle',action = "store_true", dest = "pickle", default = False,\
        help="Save a pickle of all data to PICKLE_FILE (If the RESULTS_FILE is AAAbbb.xyz, the PICKLE_FILE\
        is AAAbbb.pickle.")
result = parser.parse_args()

try:
    f = open(result.DATA_FILE,'r')
except IOError:
    if result.DATA_FILE == '':
        print "\nNo datafile given.\n"
    else:
        print  "\nCannot find the file %s, please check again.\n" % result.DATA_FILE
    parser.print_help()
    sys.exit()

# default: run all scenarios.
if not (result.twonash or result.threenash or result.twoopt or result.threeopt or result.lookahead):
    result.twonash = result.threenash = result.twoopt = result.threeopt = result.lookahead = True

##########################################################################

# Read DATA_FILE, initialize data structures, and run the myopic scenario (base case scenario: always runs).

#r1,r2,r3 = src.dataops.initialize()
initialdata = src.dataops.datainit(f)
com = src.dataops.commondata(initialdata)
Dataspace = list()
(r1,r2,r3,r4) = initialdata.get_regiondata()
Dataspace.append((com,r1,r2,r3,r4))
del initialdata
f.close()
labels = ["MYOPIC", "ONE REGION LOOKS AHEAD", "TWO NASH", "THREE NASH", "TWO OPTIMIZED", "THREE OPTIMIZED"]
Myopic = src.dataops.alldata(r1,r2,r3,r4,com,labels[0])
myopic(Myopic.get(REGION[0]),Myopic.get(REGION[1]),Myopic.get(REGION[2]),Myopic.get(REGION[3]),Myopic.WORLD,com)
Dataspace.append(Myopic)

########################################################################

# Run scenarios according to command line options (default: run  all)

# threemyopiconelookahead(r1,r2,r3,r4,...): r1 looks ahead one period, r2, r3 and r4 are myopic.
if result.lookahead:
    Onelookahead = src.dataops.alldata(r1,r2,r3,r4,com,labels[1])
    threemyopiconelookahead(Onelookahead.get(REGION[0]),Onelookahead.get(REGION[1]),\
            Onelookahead.get(REGION[2]),Onelookahead.get(REGION[3]),Onelookahead.WORLD,com,init_grid_size=40,precision=0.1)
    Dataspace.append(Onelookahead)

# onemyopictwonash(r1,r2,r3,r4,...): r1 and r2 play a two region Nash game with one period look ahead, r3 and r4  myopic.
if result.twonash:
    Twonash = src.dataops.alldata(r1,r2,r3,r4,com,labels[2])
    twomyopictwonash(Twonash.get(REGION[0]),Twonash.get(REGION[1]),\
            Twonash.get(REGION[2]),Twonash.get(REGION[3]),Twonash.WORLD,com,init_grid_size=40,precision=0.5)
    Dataspace.append(Twonash)

# threenash(r1,r2,r3,r4,...): r1, r2 and r3 play a three region Nash game where they look ahead one period, r4 is myopic.
if result.threenash:
    Threenash = src.dataops.alldata(r1,r2,r3,r4,com,labels[3])
    threenash(Threenash.get(REGION[0]),Threenash.get(REGION[1]),\
            Threenash.get(REGION[2]),Threenash.get(REGION[3]),Threenash.WORLD,com,init_grid_size=40,precision=0.5)
    Dataspace.append(Threenash)

# twooptimized(r1,r2,r3,r4,...): r1 and r2 solve the two region two period optimial green energy deployment problem, r3 and r4 are myopic.
if result.twoopt:
    Twoopt = src.dataops.alldata(r1,r2,r3,r4,com,labels[4])
    twooptimized(Twoopt.get(REGION[0]),Twoopt.get(REGION[1]),
            Twoopt.get(REGION[2]),Twoopt.get(REGION[3]),Twoopt.WORLD,com,init_grid_size=100,precision=0.5)
    Dataspace.append(Twoopt)

# threeoptimized(r1,r2,r3,r4,...): r1, r2 nd r3 solve the three region two period optimal green energy deployment problem, r4  is myopic.
if result.threeopt:
    Threeopt = src.dataops.alldata(r1,r2,r3,r4,com,labels[5])
    threeoptimized(Threeopt.get(REGION[0]),Threeopt.get(REGION[1]),\
            Threeopt.get(REGION[2]), Threeopt.get(REGION[3]),Threeopt.WORLD,com,init_grid_size=100,precision=0.5)
    Dataspace.append(Threeopt)
#
###################################################################


# Write the RESULTS_FILE.

fout = open(result.outputfile,'w')
src.output.printresults(fout,Dataspace)
fout.close()

# Write the PICKLE_FILE.

if result.pickle:
    a = result.outputfile.split('.')
    if len(a) >= 1:
        a.pop()
    a.append('pickle')
    picklefile ='.'.join(a)
    fout = open(picklefile,'w')
    pickle.dump(Dataspace,fout)
    print "Pickling results to file %s.\n" % picklefile
    fout.close()

#if __name__ == '__main__':
#    main()


